package bg.btanev.eightyfour.gwtfacade.commandhandler;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.Validate;

import bg.btanev.eightyfour.domain.Target;
import bg.btanev.eightyfour.gwtfacade.converter.DtoConverter;
import bg.btanev.eightyfour.service.TargetService;
import bg.btanev.eightyfour.shared.command.CommandResult;
import bg.btanev.eightyfour.shared.command.target.FindTargetsCommand;
import bg.btanev.eightyfour.shared.command.target.FindTargetsInput;
import bg.btanev.eightyfour.shared.dto.TargetDto;

/**
 *
 * @author B.Tanev
 *
 */
public class FindTargetCommandHandler
		extends
		GenericCommandHandler<FindTargetsInput, ArrayList<TargetDto>, CommandResult<FindTargetsInput, ArrayList<TargetDto>>, FindTargetsCommand> {

	private final TargetService targetService;
	private final DtoConverter converter;

	public FindTargetCommandHandler(TargetService targetService, DtoConverter converter) {
		super();

		Validate.notNull(targetService);
		Validate.notNull(converter);

		this.targetService = targetService;
		this.converter = converter;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected ArrayList<TargetDto> doExecuteInternal(FindTargetsInput attachedInput) {
		String fName = null;
		String lName = null;
		String email = null;

		if (attachedInput != null) {
			fName = attachedInput.getFirstName();
			lName = attachedInput.getLastName();
			email = attachedInput.getEmail();
		}

		List<Target> targets = targetService.findBySearchDetails(fName, lName, email);
		ArrayList result = converter.collectionDomainToDto(targets, 2);

		return result;
	}

	@Override
	protected CommandResult<FindTargetsInput, ArrayList<TargetDto>> packCommandResult(FindTargetsInput input,
			ArrayList<TargetDto> detachedResult) {

		return new CommandResult<FindTargetsInput, ArrayList<TargetDto>>(input, detachedResult);
	}

	@Override
	public FindTargetsInput attach(FindTargetsInput input) {
		return input;
	}

	@Override
	public ArrayList<TargetDto> detach(ArrayList<TargetDto> result) {
		return result;
	}

}
